<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <h1 class="login-title">登录</h1>
        <p class="login-subtitle">欢迎使用RAG AI应用管理系统</p>
      </div>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            size="large"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>
        
                 <el-form-item>
           <div class="form-options">
             <el-checkbox v-model="rememberMe" @click="isRemember">记住密码</el-checkbox>
             <el-link type="primary" class="forgot-password" @click="goToForgot">忘记密码？</el-link>
           </div>
         </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="login-button"
            :loading="loading"
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-footer">
        <p>还没有账号？ <el-link type="primary" @click="goToRegister">立即注册</el-link></p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { login } from '@/api/auth'
import { userStorage } from '@/utils/storage'
import { useUserStore } from '@/stores/user'
import tokenMonitor from '@/utils/tokenMonitor'
const router = useRouter()
const route = useRoute()
const loginFormRef = ref()
const loading = ref(false)
const rememberMe = ref(false)
let userStore=useUserStore()
const loginForm = ref({
  username: 'admin',
  password: '123456'
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

onMounted(()=>{
  // 检查是否有从注册页面传递过来的用户名
  const usernameFromRegister = route.query.username
  if (usernameFromRegister) {
    loginForm.value.username = usernameFromRegister
    // 清除查询参数，避免刷新页面后仍然显示
    router.replace({ path: '/login', query: {} })
  }
  
  let storageRemember = JSON.parse(localStorage.getItem("rememberMe"))
  rememberMe.value = !!storageRemember // 只在本地存储为 true 时才勾选
  if (storageRemember) {
    loginForm.value = userStore.user
  }
})

//记住密码框勾选
let isRemember=()=>{
  localStorage.setItem("rememberMe", rememberMe.value)
}

const handleLogin = async () => {
  try {
    if (!loginFormRef.value) return

    const valid = await loginFormRef.value.validate()
    if (!valid) return

    loading.value = true
    console.log('开始登录:', loginForm.value)
    
    // 调用实际的登录API
    const response = await login({
      Username: loginForm.value.username,
      Password: loginForm.value.password
    })
    
    console.log('登录响应:', response)
    console.log('响应类型:', typeof response)
    console.log('响应结构:', JSON.stringify(response, null, 2))
    
    // 由于request.js的响应拦截器已经提取了response.data
    // 所以这里的response实际上就是后端返回的数据
    if (!response) {
      throw new Error('登录响应数据无效')
    }
    
    // 检查响应是否成功
    if (response.code !== 200) {
      throw new Error(response.message || '登录失败')
    }
    
    // 从嵌套结构中提取数据
    const { accessToken, refreshToken, user } = response.data
    
    console.log('登录成功，用户信息:', user)
    console.log('访问令牌:', accessToken)
    console.log('刷新令牌:', refreshToken)
    
    // 保存用户信息
    userStore.remember(loginForm.value)
    localStorage.setItem("userInfo", JSON.stringify(user))
    userStore.setUserInfo(user)
    localStorage.setItem("users", JSON.stringify(userStore.user))
    
    // 登录成功处理
    ElMessage.success('登录成功！')
    
    // 保存token和refresh token
    if (accessToken) {
      userStorage.setToken(accessToken)
      if (refreshToken) {
        userStorage.setRefreshToken(refreshToken)
      }
    }
    
    // 启动token监控
    tokenMonitor.start()
    
    // 跳转到仪表盘页面（避免与路由守卫冲突）
    console.log('准备跳转到:', '/admin/dashboard')
    
    // 使用await确保跳转完成
    try {
      await router.push('/admin/dashboard')
      console.log('跳转成功')
    } catch (error) {
      console.error('跳转失败:', error)
      // 如果跳转失败，尝试跳转到文档管理
      await router.push('/admin/documents')
    }
    
  } catch (error) {
    console.error('登录失败:', error)
    
    // 显示具体的错误信息
    let errorMessage = '登录失败，请稍后重试'
    
    if (error.response) {
      // 服务器返回错误
      const { status, data } = error.response
      if (data && data.message) {
        errorMessage = data.message
      } else if (status === 401) {
        errorMessage = '用户名或密码错误'
      } else if (status === 500) {
        errorMessage = '服务器内部错误，请稍后重试'
      } else if (status === 404) {
        errorMessage = '登录接口不存在'
      } else {
        errorMessage = `请求失败 (${status})`
      }
    } else if (error.request) {
      // 网络错误
      errorMessage = '网络连接失败，请检查网络设置'
    } else if (error.message) {
      // 其他错误
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
    
  } finally {
    loading.value = false
  }
}

const goToForgot = () => {
  router.push('/forgot-password')
}
const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: url('@/assets/images/login-bg.svg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  padding: 20px;
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
  margin: 0;
  padding: 20px;
}

.login-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(2px);
  z-index: 1;
  animation: backgroundPulse 8s ease-in-out infinite;
}

@keyframes backgroundPulse {
  0%, 100% { opacity: 0.1; }
  50% { opacity: 0.15; }
}

.login-card {
  position: relative;
  z-index: 2;
  background: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(16px) saturate(180%);
  -webkit-backdrop-filter: blur(16px) saturate(180%);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 50px;
  width: 100%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  margin: 0;
}

@keyframes cardFloat {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-12px); }
}



@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-title {
  font-size: 32px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 12px 0;
  animation: titleGlow 4s ease-in-out infinite;
}

@keyframes titleGlow {
  0%, 100% { text-shadow: 0 0 8px rgba(102, 126, 234, 0.4); }
  50% { text-shadow: 0 0 25px rgba(102, 126, 234, 0.8); }
}

.login-subtitle {
  color: #7f8c8d;
  font-size: 16px;
  margin: 0;
}

.login-form {
  margin-bottom: 20px;
}

.login-form :deep(.el-form-item) {
  margin-bottom: 25px;
}

.login-form :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.login-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  border-color: rgba(102, 126, 234, 0.3);
}

.login-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
  border-color: #667eea;
}

.login-button {
  width: 100%;
  height: 52px;
  border-radius: 8px;
  font-size: 18px;
  font-weight: 500;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.login-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.login-button:hover::before {
  left: 100%;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(102, 126, 234, 0.3);
}

.login-button:active {
  transform: translateY(0);
}

 .form-options {
   display: flex;
   justify-content: space-between;
   align-items: center;
   width: 100%;
 }

 .forgot-password {
   font-size: 14px;
 }

.login-footer {
  text-align: center;
  color: #7f8c8d;
  font-size: 14px;
}

.login-footer p {
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-container {
    padding: 10px;
  }
  
  .login-card {
    padding: 40px 25px;
    margin: 0;
    max-height: 95vh;
    max-width: 450px;
  }
  
  .login-title {
    font-size: 28px;
  }
}
</style>
